package com.jvup.common.dal.dao;

import androidx.room.Room;

import com.jvup.common.SummerApp;
import com.jvup.common.basic.ObjectUtil;

import java.util.HashMap;

public final class DatabaseFactory {

    private static final DatabaseFactory FACTORY = new DatabaseFactory();

    private final String DB_SUFFIX = ".db";

    // volatile
    private final HashMap<String, BaseDatabase> databaseMapper = new HashMap<>();

    private DatabaseFactory() {}

    public static synchronized <T extends BaseDatabase> T create(Class<T> databaseClass) {
        String nameKey = databaseClass.getCanonicalName();
        T database = (T) FACTORY.databaseMapper.get(nameKey);
        if(ObjectUtil.isNull(database)) {
            database = Room.databaseBuilder(SummerApp.getContext(), databaseClass, nameKey + FACTORY.DB_SUFFIX).build();
            FACTORY.databaseMapper.put(nameKey, database);
        }
        return database;
    }

}
